import axios from 'axios'
import store from '@/store'
import router from '@/router'
export const baseURL = 'https://apipc-xiaotuxian-front.itheima.net/'

import { ElMessage } from 'element-plus'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

instance.interceptors.request.use(
  config => {
    // 用户信息
    const { profile } = store.state.user
    if (profile.token) {
      config.headers.Authorization = `Bearer ${profile.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

instance.interceptors.response.use(
  res => {
    return res.data
  },
  err => {
    // 401 进入函数
    if (err.response && err.response.status === 401) {
      // 清空无效信息
      store.commit('user/setUser', {})
      // 跳转到登录页面
      // 跳转到当前路由
      const fullPath = encodeURIComponent(router.currentRoute.value.fullPath) //  encodeURIComponent 转 uri 码
      router.push('/login?redirectUrl=' + fullPath)
    }
    if(err.response && err.response.data) {
      ElMessage.error(err.response.data.message)
    }else{
      ElMessage.error(err.message)
    }
    return Promise.reject(err)
  }
)
export default instance
